﻿using ZilLion.Service.Core.ConfigManager.Manager;

namespace ZilLion.Service.Core.Snowflake
{
    public class SnowflakeIdCreater
    {
        private  IdWorker _idWorker;

        private  SnoWorKer _snoWorKer;

        public string GetNextSno()
        {
            return _snoWorKer.GetNewSno();
        }

        public long GetNextId()
        {
            return _idWorker.NextId();
        }

        #region Singleton

        private static SnowflakeIdCreater _instance;
        private static readonly object Instancelocker = new object();


        private SnowflakeIdCreater()
        {
            //需考虑将前缀的管理包含进来，每种前缀分别对应一个worker实例；
            //同一个应用端的所有worker共用一个workerid；
            var workid = ZilLionConfigurationManager.GetConfigInstance<SnowflakeConfig>().WorkerId;
            _idWorker = new IdWorker(workid);
            _snoWorKer = new SnoWorKer(workid);
        }

        public void Init()
        {
            var workid = ZilLionConfigurationManager.GetConfigInstance<SnowflakeConfig>().WorkerId;
            _idWorker = new IdWorker(workid);
            _snoWorKer = new SnoWorKer(workid);
        }

        public static SnowflakeIdCreater Instance()
        {
            //没有第一重 instance == null 的话，每一次有线程进入 GetInstance()时，均会执行锁定操作来实现线程同步，
            //非常耗费性能 增加第一重instance ==null 成立时的情况下执行一次锁定以实现线程同步
            if (_instance == null)
                lock (Instancelocker)
                {
                    //Double-Check Locking 双重检查锁定
                    if (_instance == null) _instance = new SnowflakeIdCreater();
                }
            return _instance;
        }

        public void Dispose()
        {
        }

        ~SnowflakeIdCreater()
        {
            Dispose();
        }

        #endregion
    }
}